from rest_framework import serializers
from .models_test import User
import re


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id'
            'username',
            'password',
            'mobile'
        ]
        extra_kwargs = {
            'username': {'min_length': 8, 'max_length': 20},
            'password': {'min_length': 5, 'max_length': 20, 'write_only': True},
        }

    def validate(self, attrs):
        # 用户名,密码只校验字符长度
        username = attrs.get('username')
        password = attrs.get('password')
        mobile = attrs.get('mobile')
        if not all([password, mobile, username]):
            raise serializers.ValidationError('缺少必传参数')

        if not re.match(r'1[3-9]\d{9}', mobile):
            raise serializers.ValidationError('手机号格式错误')
        return attrs

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user
